package com.greedy.controller;

import cn.hutool.core.bean.BeanUtil;
import com.greedy.bean.dto.LoginFormDTO;
import com.greedy.bean.dto.UserDTO;
import com.greedy.bean.pojo.User;
import com.greedy.bean.pojo.UserInfo;
import com.greedy.interceptor.UserHolder;
import com.greedy.service.UserService;
import com.greedy.utils.Result;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import static com.greedy.constants.CommentConstants.LOGIN_USER_KEY;

/**
 * @Author: Yanxy
 * @Date: Created in:2022-12-24
 * Description: 用户
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    UserService userService;

    @Resource
    StringRedisTemplate stringRedisTemplate;

    /**
     * 发送手机验证码
     */
    @PostMapping("/code")
    public Result sendCode(@RequestParam("phone") String phone) {
        // 发送短信验证码并保存验证码
        return userService.sendCode(phone);
    }

    /**
     * 登录功能
     *
     * @param loginForm 登录参数，包含手机号、验证码；或者手机号、密码
     */
    @PostMapping("/login")
    public Result login(@RequestBody LoginFormDTO loginForm, HttpSession session) {
        // 实现登录功能
        return userService.login(loginForm, session);
    }

    /**
     * 我的页面-用户信息
     *
     * @return 用户信息
     */
    @GetMapping("/me")
    public Result me() {
        // 获取当前登录的用户并返回
        UserDTO user = UserHolder.getUser();
        return Result.ok(user);
    }

    /**
     * 登出功能
     *
     * @return 无
     */
    @PostMapping("/logout")
    public Result logout(HttpServletRequest request) {
        // 获取请求头中的token
        String token = request.getHeader("authorization");
        // 删除Redis中的Token
        stringRedisTemplate.delete(LOGIN_USER_KEY + token);
        return Result.ok();
    }

    /**
     * 查看详情
     * @param userId userId
     * @return UserInfo
     */
    @GetMapping("/info/{id}")
    public Result info(@PathVariable("id") Long userId){
        UserInfo userInfo = userService.info(userId);
        if (userInfo == null) {
            // 没有详情，应该是第一次查看详情
            return Result.ok();
        }
        userInfo.setCreateTime(null);
        userInfo.setUpdateTime(null);
        return Result.ok(userInfo);
    }

    /**
     * 查询用户
     * @param userId
     * @return
     */
    @GetMapping("/{id}")
    public Result queryUserById(@PathVariable("id") Long userId){
        return Result.ok(userService.getById(userId));
    }

    @PostMapping("/sign")
    public Result sign(){
        userService.sign();
        return Result.ok();
    }

    @GetMapping("/sign/count")
    public Result signCount(){
        return Result.ok(userService.signCount());
    }
}
